# -*- coding:UTF-8 -*-
import threading
import time
import json

import multiprocessing
from multiprocessing import Manager, Value, Queue, Pool, Process, Lock
from multiprocessing import queues
from helpers.baglisthelper import BagListHelper
from helpers.sockethelper import SocketHelper
from helpers.threadhelper import ThreadHelper
from helpers.tcphelper import TcpHelper
from events import build_event

# 永久的进程：
# XXXXXXXXXXXXXX1.socket的监听（cotrol中不断监听）
# 2.管理任务添加和删除的进程，添加main_thread类
# 3.反馈任务->当任务结束后要向前台报告json
# 4.定时器控制器

# 进程元素，进程池，反馈函数, timer
sk_h = SocketHelper()
tcp_h = TcpHelper("127.0.0.01", 8080)


def wait_function(status, result, ):  # 等待停止 停止后将内容添加到另一个列表，由requ函数返回
    if status:
        try:
            tcp_h.response_list.put(result)
        except Exception as e:
            print(e)
        # sk_h.request(result)
    pass


def loop_function(loop_map, tcp_helper):
    thrd_h = ThreadHelper(10, 10)
    remove_list = []
    for response in tcp_helper.tcp_response_loop():
        for key, value in loop_map.items():
            print("loop running bag=" + value.name)
            if not value.get_loop():
                remove_list.append(key)
                continue
            thrd_h.run(value.loop_run, (key,), wait_function)
        
        for key in remove_list:
            del loop_map[key]
        
        remove_list = []
        
        if response == False:
            time.sleep(2)
        else:
            time.sleep(1)


def main_process(tcp_helper: TcpHelper):
    from events import Event
    from helpers.baglisthelper import BagListHelper as BagsHelper
    global tcp_h
    bag_h = BagsHelper()
    manager = Manager()
    loop_map = manager.dict()
    thrd_h = ThreadHelper(5, 5)
    thread_name = 0
    tcp_helper.response_list = Queue()
    tcp_h = tcp_helper
    t = Process(target=loop_function, args=(loop_map, tcp_h))
    t.start()
    is_event = False
    for request in tcp_h.tcp_request_loop():
        while request != "Null":
            rev_event = build_event(request)
            try:
                is_event = isinstance(rev_event, Event)
            except:
                is_event = False
            if is_event:
                # sk_h.reply(rev_event.time)  # 当没有收到成功删除时需要有操作，原地踏步，如果载入失败也要汇报错误
                bag = bag_h.find_bag(rev_event.bag)
                if bag is None:
                    break
                mod = bag.find_module(rev_event.id)
                if mod == "warning":
                    continue
                
                if mod.is_enable(bag):
                    thrd_h.run(mod.happen_event, (rev_event,), wait_function)
                    thread_name += 1
                    if mod.get_loop():
                        time.sleep(0.5)
                        loop_map[str(thread_name)] = mod
            break
